import React, { useState, useEffect } from "react";
import { Route, Routes, useNavigate, Link } from 'react-router-dom';
import { Button, Drawer, Form, Avatar, Divider, List, Skeleton, Space, message } from 'antd';
import InfiniteScroll from 'react-infinite-scroll-component';
import { PlusOutlined, LikeOutlined, MessageOutlined, EyeOutlined, LikeFilled } from '@ant-design/icons';
import intl from 'react-intl-universal';
import $ from 'jquery';
import ArticleEdit from "../article/addArticleDrawer.js";
import { storage } from "../../utils/localstorage.js";
import SearchBar from "./searchBar.js";
import './knowledge.css';



const Knowledge = () => {
    // 获取文章数据
    const [hasChange, setHasChange] = useState(true);
    const [articleData, setArticleData] = useState([]);
    useEffect(() => {
        const getArticleData = () => {
            $.ajax({
                url: '/home/article',
                type: 'post',
                dataType: 'json',
                success: function(result) {
                    if (result.status === 1) {
                        setArticleData(result.data);
                    }
                },
                error: function(err) {
                    alert(JSON.stringify(err));
                },
            });
        };
        hasChange && getArticleData();
        setHasChange(false);
    }, [hasChange]);


    // 创作、修改文章时，弹出的抽屉
    const [drawerVisible, setDrawerVisible] = useState(false);
    const showDrawer = () => {
        setDrawerVisible(true);
    };
    const closeDrawer = () => {
        setDrawerVisible(false);
    };


    // 文章列表
    const data = articleData.map((item) => ({
        href: '',
        id: item.aid,
        title: item.title,
        summary: item.summary,
        content: item.content,
        cover: item.cover,
        author: item.author,
        kind: item.kind,
        views: item.views,
        likes: item.likes,
        comments: item.comments,
    }));


    // 点赞。id即文章id；type即类型，1表示点赞，-1表示取消点赞
    const doLike = (id, type) => {
        let data = {};
        if (type === 1) {
        data = {uid:storage.get('user').uid, aid:id, type:type, pType:3};
        } else {
        data = {uid:storage.get('user').uid, aid:id, type:type, pType:4};
        }
        $.ajax({
        url: '/home/article/like',
        type: 'post',
        data: data,
        dataType: 'json',
        success: function(result) {
            setHasChange(true);
        },
        error: function(err) {
            message.info('网络繁忙，请稍后再试');
        }
        })
    };


    // 浏览文章，浏览量+1，作者积分增加
    const readOnce = (id, author) => {
        $.ajax({
        url: '/home/article/read',
        type: 'post',
        data: {aid:id, author:author},
        dataType: 'json',
        success: function(result) {
            setHasChange(true);
        },
        });
    };


    return (
        <div style={{ backgroundColor: '#FFF', }}>
            <div style={{display:'flex'}}>
                <SearchBar callback={setArticleData} />
                <Button type="primary" onClick={showDrawer} icon={<PlusOutlined />} className='createArticle'>
                    {intl.get('createArticle')}
                </Button>
            </div>
            <div id="scrollableDiv" style={{ height: '700px', overflow: 'scroll', padding: '0 16px', border: '1px solid rgba(140, 140, 140, 0.35)', }}>
                <InfiniteScroll dataLength={data.length} hasMore={data.length < 50}
                    endMessage={<Divider plain>It is all, nothing more 🤐</Divider>}
                    scrollableTarget="scrollableDiv"
                >
                    <List
                        itemLayout="vertical"
                        size="large"
                        loading={false}
                        dataSource={data}
                        renderItem={(item) => (
                            <List.Item
                                key={item.id}
                                actions={[
                                    <Space>
                                        <EyeOutlined className='view' />
                                        {item.views}
                                    </Space>,
                                    <Space>
                                        { 
                                            (item.likes.indexOf(storage.get('user').uid) === -1) ? 
                                            <LikeOutlined className='like' onClick={() => doLike(item.id, 1)} /> : 
                                            <LikeFilled className='like' onClick={() => doLike(item.id, -1)} style={{color:'red'}} />
                                        }
                                        {item.likes.length}
                                    </Space>,
                                    <Space>
                                        <MessageOutlined className='comment' />
                                        {item.comments.length}
                                    </Space>,
                                ]}
                                extra={<img width={272} height={120} alt="cover" src={item.cover} />}
                            >
                                <Link to={`/details/${item.id}`} target='_blank' onClick={() => readOnce(item.id, item.author)}>
                                    <List.Item.Meta title={item.title} description={item.summary} />
                                    {/* {item.content} */}
                                </Link>
                            </List.Item>
                        )}
                    />
                </InfiniteScroll>
            </div>
            <Drawer title="发布文章" width={'80%'} onClose={closeDrawer} visible={drawerVisible}
                bodyStyle={{ paddingBottom: 80, }} destroyOnClose={true}
                extra={
                    <Space>
                        <Button onClick={closeDrawer}>Cancel</Button>
                    </Space>}
            >
                <ArticleEdit closeDrawer={closeDrawer} setHasChange={setHasChange} />
            </Drawer>
        </div>
    );
};

export default Knowledge;